package com.xsoft.navigation.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.SensorManager;
import android.location.Location;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.Text;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.CoordinateConverter;
import com.baidu.mapapi.utils.DistanceUtil;
import com.baidu.mapapi.walknavi.WalkNavigateHelper;
import com.baidu.mapapi.walknavi.adapter.IWEngineInitListener;
import com.baidu.mapapi.walknavi.adapter.IWRoutePlanListener;
import com.baidu.mapapi.walknavi.model.WalkRoutePlanError;
import com.baidu.mapapi.walknavi.params.WalkNaviLaunchParam;
import com.baidu.mapapi.walknavi.params.WalkRouteNodeInfo;
import com.ficat.easyble.BleManager;
import com.xsoft.common.util.SharePrefUtils;
import com.xsoft.location.LocationEvent;
import com.xsoft.location.LocationManager;
import com.xsoft.navigation.R;
import com.xsoft.navigation.databinding.ActivityMainBinding;
import com.xsoft.navigation.pdr.DeviceAttitudeHandler;
import com.xsoft.navigation.pdr.StepDetectionHandler;
import com.xsoft.navigation.pdr.StepPositioningHandler;
import com.xsoft.permission.Permission;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;

public class MainActivity extends BaseActivity<ActivityMainBinding> implements StepDetectionHandler.StepDetectionListener,
        View.OnClickListener {
    private static final String TAG = MainActivity.class.getSimpleName();
    private static final String KEY_LAST_LAT = "last_lat";
    private static final String KEY_LAST_LON = "Last_lon";
    private static final String KEY_LAST_TIME = "Last_time";
    private static final String KEY_LAST_ALT = "Last_alt";
    private static final String KEY_LAST_SPEED = "Last_speed";
    private static final String KEY_LAST_POSITION = "Last_position";
    private static final int ENABLE_BLUETOOTH_REQUEST_CODE = 100;
    private BaiduMap baiduMap;
    /*导航起终点Marker，可拖动改变起终点的坐标*/
    private Marker startMarker;
    private Marker endMarker;
    private Polyline polyline;
    private Text distanceText;
    private LatLng startPt;
    private LatLng endPt;
    private BitmapDescriptor bdStart = BitmapDescriptorFactory
            .fromResource(R.drawable.icon_start);
    private BitmapDescriptor bdEnd = BitmapDescriptorFactory
            .fromResource(R.drawable.icon_end);
    //惯性导航
    private StepDetectionHandler stepDetectionHandler;
    private StepPositioningHandler stepPositioningHandler;
    private DeviceAttitudeHandler deviceAttitudeHandler;
    private boolean isInertialNavigation;

    @Override
    protected void initView() {
        baiduMap = binding.mapview.getMap();
        binding.connectBle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //是否支持BLE
                if (!BleManager.supportBle(MainActivity.this)) {
                    Toast.makeText(MainActivity.this, "您的设备不支持蓝牙", Toast.LENGTH_SHORT);
                    return;
                }
                //蓝牙是否打开
                if (BleManager.isBluetoothOn()) {
                    startActivity(new Intent(MainActivity.this, BleActivity.class));
                } else {
                    //显示dialog请求用户打开蓝牙，需在传入的activity的onActivityResult中处理请求结果
                    BleManager.enableBluetooth(MainActivity.this, ENABLE_BLUETOOTH_REQUEST_CODE);
                }
            }
        });
        binding.beginNavi.setOnClickListener(this);
        binding.location.setOnClickListener(this);
        binding.navigation.setOnClickListener(this);
        if (readLastLocation()) {
            initMapStatus(startPt);
            initOverlay();
        }
        baiduMap.setOnMarkerDragListener(new BaiduMap.OnMarkerDragListener() {
            @Override
            public void onMarkerDrag(Marker marker) {
                if (marker == startMarker) {
                    stopLocation();
                    startPt = marker.getPosition();
                } else if (marker == endMarker) {
                    endPt = marker.getPosition();
                }
            }

            @Override
            public void onMarkerDragEnd(Marker marker) {

            }

            @Override
            public void onMarkerDragStart(Marker marker) {

            }
        });
    }

    @Override
    @Permission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    protected void initData() {
        startLocation();
        EventBus.getDefault().register(this);
        isInertialNavigation = false;
    }

    private boolean readLastLocation() {
        String lat = SharePrefUtils.getStringValue(KEY_LAST_LAT, null);
        String lon = SharePrefUtils.getStringValue(KEY_LAST_LON, null);
        if (!TextUtils.isEmpty(lat) && !TextUtils.isEmpty(lon)) {
            try {
                startPt = new LatLng(Double.valueOf(lat), Double.valueOf(lon));
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        String lat = com.xsoft.navigation.ble.BleManager.getInstance().getRecordLat();
        String lon = com.xsoft.navigation.ble.BleManager.getInstance().getRecordLon();
        if (!TextUtils.isEmpty(lat) && !TextUtils.isEmpty(lon)) {
            try {
                LatLng latLng = new LatLng(Double.valueOf(lat), Double.valueOf(lon));
                CoordinateConverter converter = new CoordinateConverter();
                converter.from(CoordinateConverter.CoordType.GPS);
                converter.coord(latLng);
                endPt = converter.convert();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocationManager.getInstance().stop();
        EventBus.getDefault().unregister(this);
        bdStart.recycle();
        bdEnd.recycle();
        stopLocation();
        stopInertialNavigation();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LocationEvent event) {
        startPt = event.latLng;
        initMapStatus(event.latLng);
        initOverlay();
        SharePrefUtils.saveValue(KEY_LAST_LAT, String.valueOf(startPt.latitude));
        SharePrefUtils.saveValue(KEY_LAST_LON, String.valueOf(startPt.longitude));
        stopLocation();
    }

    // 获取导航控制类
    // 引擎初始化
    private void initNaviEngine() {
        WalkNavigateHelper.getInstance().initNaviEngine(this, new IWEngineInitListener() {
            @Override
            public void engineInitSuccess() {
                //引擎初始化成功的回调
                routePlanWithRouteNode();
            }

            @Override
            public void engineInitFail() {
                //引擎初始化失败的回调
                WalkNavigateHelper.getInstance().unInitNaviEngine();
            }
        });
    }

    //发起路线规划
    private void routePlanWithRouteNode() {
        WalkRouteNodeInfo walkStartNode = new WalkRouteNodeInfo();
        walkStartNode.setLocation(startPt);
        WalkRouteNodeInfo walkEndNode = new WalkRouteNodeInfo();
        walkEndNode.setLocation(endPt);
        WalkNaviLaunchParam walkParam = new WalkNaviLaunchParam().startNodeInfo(walkStartNode).endNodeInfo(walkEndNode);
        WalkNavigateHelper.getInstance().routePlanWithRouteNode(walkParam, new IWRoutePlanListener() {
            @Override
            public void onRoutePlanStart() {
                //开始算路的回调
            }

            @Override
            public void onRoutePlanSuccess() {
                //算路成功
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, WNaviGuideActivity.class);
                startActivity(intent);
            }

            @Override
            public void onRoutePlanFail(WalkRoutePlanError walkRoutePlanError) {
                //算路失败的回调
            }
        });
    }

    /**
     * 初始化地图状态
     *
     * @param latLng
     */
    private void initMapStatus(LatLng latLng) {
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(latLng).zoom(15);
        baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
    }

    /**
     * 初始化导航起终点Marker
     */
    private void initOverlay() {
        if (startMarker == null) {
            MarkerOptions ooA = new MarkerOptions().position(startPt).icon(bdStart)
                    .zIndex(9).draggable(true);
            startMarker = (Marker) (baiduMap.addOverlay(ooA));
            startMarker.setDraggable(true);
        } else {
            startMarker.setPosition(startPt);
        }
        if (endPt == null) {
            endPt = startPt;
        }
        if (endMarker == null) {
            MarkerOptions ooB = new MarkerOptions().position(endPt).icon(bdEnd)
                    .zIndex(5);
            endMarker = (Marker) (baiduMap.addOverlay(ooB));
            /**陳廣平
             * 改為終點不可拖動endMarker.setDraggable(true);
             */
            endMarker.setDraggable(false);

        } else {
            endMarker.setPosition(endPt);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ENABLE_BLUETOOTH_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            if (BleManager.isBluetoothOn()) {
                startActivity(new Intent(MainActivity.this, BleActivity.class));
            } else {
                Toast.makeText(MainActivity.this, "打开蓝牙失败", Toast.LENGTH_SHORT);
            }
        }
    }

    @Override
    public void newStep(float stepSize) {
        if (!isInertialNavigation) {
            return;
        }
        Location newloc = stepPositioningHandler.computeNextStep(stepSize, deviceAttitudeHandler.orientationVals[0]);
        Log.d(TAG, newloc.getLatitude() + " " + newloc.getLongitude() + " " + deviceAttitudeHandler.orientationVals[0]);
        drawInertialNavigationInfo(new LatLng(newloc.getLatitude(), newloc.getLongitude()), endPt);
    }

    private void startLocation() {
        binding.location.setImageResource(R.drawable.ic_gps_selected);
        LocationManager.getInstance().requestLocation(this);
    }

    private void stopLocation() {
        binding.location.setImageResource(R.drawable.ic_gps_normal);
        LocationManager.getInstance().stop();
    }

    /**
     * 开启惯性导航
     */
    private void startInertialNavigation() {

        if (startPt == null) {
            toast("请设置起点位置");
            return;
        }
        if (LocationManager.getInstance().isStarted()) {
            stopLocation();
        }
        isInertialNavigation = true;
        binding.navigation.setImageResource(R.drawable.ic_navigation_selected);
        SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        stepDetectionHandler = new StepDetectionHandler(sensorManager);
        stepDetectionHandler.setStepListener(this);
        stepDetectionHandler.start();
        stepPositioningHandler = new StepPositioningHandler();
        Location location = new Location(android.location.LocationManager.GPS_PROVIDER);
        location.setLatitude(startPt.latitude);
        location.setLongitude(startPt.longitude);
        stepPositioningHandler.setCurrentLocation(location);
        deviceAttitudeHandler = new DeviceAttitudeHandler(sensorManager);
        deviceAttitudeHandler.start();
        clearOverlay();
        drawInertialNavigationInfo(startPt, endPt);
    }

    /**
     * 关闭惯性导航
     */
    private void stopInertialNavigation() {
        isInertialNavigation = false;
        binding.navigation.setImageResource(R.drawable.ic_navigation_normal);
        if (stepDetectionHandler != null) {
            stepDetectionHandler.stop();
        }
        if (deviceAttitudeHandler != null) {
            deviceAttitudeHandler.stop();
        }
        clearOverlay();
        initOverlay();
    }

    private void drawInertialNavigationInfo(LatLng startPt, LatLng endPt) {
        //画线
        List<LatLng> points = new ArrayList<>();
        points.add(startPt);
        points.add(endPt);
        if (polyline == null) {
            OverlayOptions line = new PolylineOptions()
                    .color(Color.RED)
                    .width(5)
                    .points(points);
            polyline = (Polyline) baiduMap.addOverlay(line);
        } else {
            polyline.setPoints(points);
        }
        if (startMarker == null) {
            MarkerOptions ooA = new MarkerOptions().position(startPt).icon(bdStart)
                    .zIndex(9);
            startMarker = (Marker) (baiduMap.addOverlay(ooA));
        } else {
            startMarker.setPosition(startPt);
        }
        if (endMarker == null) {
            MarkerOptions ooB = new MarkerOptions().position(endPt).icon(bdEnd)
                    .zIndex(5);
            endMarker = (Marker) (baiduMap.addOverlay(ooB));
        } else {
            endMarker.setPosition(endPt);
        }
        if (distanceText == null) {
            //构建TextOptions对象
            OverlayOptions textOptions = new TextOptions()
                    .text((int) DistanceUtil.getDistance(startPt, endPt) + "米") //文字内容
                    .bgColor(0xAAFFFF00) //背景色
                    .fontSize(24) //字号
                    .fontColor(0xFFFF00FF) //文字颜色
                    .position(startPt);
            //在地图上显示文字覆盖物
            distanceText = (Text) baiduMap.addOverlay(textOptions);
        } else {
            distanceText.setText((int) DistanceUtil.getDistance(startPt, endPt) + "米");
        }
    }

    private void clearOverlay() {
        baiduMap.clear();
        startMarker = null;
        endMarker = null;
        polyline = null;
        distanceText = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.location:
                if (LocationManager.getInstance().isStarted()) {
                    stopLocation();
                } else {
                    startLocation();
                }
                break;
            case R.id.navigation:
                if (isInertialNavigation) {
                    stopInertialNavigation();
                } else {
                    startInertialNavigation();
                }
                break;
            case R.id.begin_navi:
                initNaviEngine();
                break;
        }
    }
}